package com.example.mytestdemo.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator

/**
 *@Author tgw
 *@Date 2023/11/10
 *@describe
 */
class MarqueeView(context: Context, attrs: AttributeSet) : View(context, attrs){

    private val text = "这是一条跑马灯信息"

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.RED
        textSize = 48f
    }



    private var offset = 0f

    private val textWidth by lazy { paint.measureText(text) }
    private var textGap = 100f

    private val animator = ValueAnimator.ofFloat(0f, textWidth + textGap).apply {
        duration = 5000
        repeatCount = ValueAnimator.INFINITE
        interpolator = LinearInterpolator()
        addUpdateListener {
            offset = it.animatedValue as Float
            invalidate()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)

        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        val textWidth = paint.measureText(text)
        val textHeight = paint.fontMetrics.bottom - paint.fontMetrics.top

        setMeasuredDimension(
            if (widthMode == MeasureSpec.EXACTLY) widthSize else textWidth.toInt(),
            if (heightMode == MeasureSpec.EXACTLY) heightSize else textHeight.toInt()
        )

    }

    override fun onDraw(canvas: Canvas) {

        canvas.clipRect(0f, 0f, textWidth + textGap, measuredHeight.toFloat())



        // 计算文字居中行高
        val textHeight = paint.fontSpacing
        val verticalCenter = measuredHeight / 2f + textHeight / 2

        // 动态计算文本间隔
        val textWidth = paint.measureText(text)
        val viewWidth = measuredWidth
        val textGap = if(textWidth < viewWidth) {
            viewWidth - textWidth
        } else {
            100f
        }

        canvas.drawText(text, -offset, verticalCenter, paint)
        canvas.drawText(text, textWidth + textGap - offset, verticalCenter, paint)


    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        animator.start()
    }

}



